package com.chenwb.concurrency.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo implements Runnable {

	final Semaphore semaphore = new Semaphore(5);

	@Override
	public void run() {
		try {
			semaphore.acquire();
			Thread.sleep(1000);
			System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + " done");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			semaphore.release();
		}


	}

	/**
	 * 执行结果：
	 * 1585797316 pool-1-thread-2 done
	 * 1585797316 pool-1-thread-6 done
	 * 1585797316 pool-1-thread-4 done
	 * 1585797316 pool-1-thread-1 done
	 * 1585797316 pool-1-thread-3 done
	 * 1585797317 pool-1-thread-5 done
	 * 1585797317 pool-1-thread-13 done
	 * 1585797317 pool-1-thread-8 done
	 * 1585797317 pool-1-thread-9 done
	 * 1585797317 pool-1-thread-7 done
	 * 1585797318 pool-1-thread-10 done
	 * 1585797318 pool-1-thread-11 done
	 * 1585797318 pool-1-thread-14 done
	 * 1585797318 pool-1-thread-12 done
	 * 1585797318 pool-1-thread-15 done
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(20);
		Runnable runnable = new SemaphoreDemo(); //新建线程时不要每次都new SemaphoreDemo(),否则每个SemaphoreDemo实例都拥有一个semaphore对象
		for (int i = 0; i < 15; i++) {
			service.submit(new Thread(runnable, "thread" + i));
		}
	}


}
